<?php
/*
	订单类
*/

class Order extends Main{

	//取得购物车商品
	public function cartGoods(){
		/* 初始化 */
		$cat_ids = array();
		$goods_list = array();

		/* 循环、统计 */
		$sql = "select c.pack_goods_id,g.goods_name,g.goods_id,g.cat_id,g.goods_sn,c.goods_attr,g.market_price,g.original_img,g.shop_price as goods_price,c.rec_id,c.goods_number,c.goods_attr_id from goods as g inner join cart as c on c.goods_id=g.goods_id where c.session_id='".USER_AGENT."' ";

		$res = $GLOBALS['db']->getAll($sql);

		$shop_price = 0;
		$market_price = 0;
		$goods_amount = 0;
		if(!is_array($res))
		{
			return array();
		}

		$pack = array();
		foreach ($res as $key=>$row)
		{
			$pack_id = $row['pack_goods_id'];
			$pack[] = $pack_id;
			$row['shop_price'] = $row['goods_price'];
			$row = $GLOBALS['Goods']->goodsFormat($row);
			$row['subtotal'] = ($row['shop_price']*$row['goods_number']);
			$row['subtotald'] = $this->priceFormat($row['subtotal']);
			$cat_ids[] = $row['cat_id'];
			$goods_list[$key]= $row;
			$shop_price+=$row['shop_price'];
			$market_price+=$row['market_price'];
			if($pack_id==0)
				$goods_amount += $row['subtotal'];
		}
		$pack = array_unique($pack);
		$pack_res = $GLOBALS['Goods']->packGoodsPrice($pack);
		$goods_amount += @$pack_res['fee']['price'];

		$total['saving']       = $this->priceFormat($market_price - $shop_price);
		if ($market_price > 0)
		{
			$total['save_money'] =  round(($market_price - $shop_price) * 100 / $market_price).'%' ;
		}

		$total['goods_amountd']  = $this->priceFormat($goods_amount);
		$total['goods_amount'] = $goods_amount;

		$result = array('goods_list' => $goods_list, 'total' => $total,'cat_ids'=>$cat_ids,'pack'=>$pack_res);
		$_SESSION[USER_AGENT]['cart_goods'] = $result;

		return $result;
	}
	//属性价格
	public function attrPrice($goods_attr_id){
		$attr_price = 0;
		if(empty($goods_attr_id))
		{
			return $attr_price;
		}
		$sql = "select attr_price from goods_attr where goods_attr_id = '".$goods_attr_id."'";

		$res = $GLOBALS['db']->getone($sql);
		return $res;
	}


	//计算总费用
	public function grandTotal($cart_goods,$shipping){

		$discount = @$_SESSION[USER_AGENT]['discount']['value'];
		$shipping_fee = $shipping['base_fee'];
		$free_money = $shipping['free_money'];

		$total = $cart_goods['total'];
		//print_r($cart_goods);
		if($total['goods_amount']>=$free_money && $free_money>0)
		{
			$shipping_fee = 0;
		}

		$grand['subtotal'] = $total['goods_amount'];
		$grand['discount'] = $discount;
		$grand['shipping_fee'] = $shipping_fee;
		$grand['grand']    = ($total['goods_amount']+$shipping_fee-$discount);
		if(($total['goods_amount']+$shipping_fee)<$discount)
		{
			$grand['grand'] = 0;
		}
		$grand['free_money'] = $free_money;
 		$grand = $this->priceFormat($grand);
		$grand['free_money'] = $free_money;

		$_SESSION[USER_AGENT]['grand'] = $grand;
		return $grand;
	}
	//取得shipping
	public function getShipping(){
		$list = $this->shippingList();
		$shipping = isset($_SESSION[USER_AGENT]['shipping']) ? $_SESSION[USER_AGENT]['shipping'] : @$list[0];
		return $shipping;
	}
	//取得payment
    public function getPayment(){
		$list = $this->paymentList();
		$payment = isset($_SESSION[USER_AGENT]['payment']) ? $_SESSION[USER_AGENT]['payment'] : @$list[0];
		return $payment;
	}
	//检查订单信息
	public function checkOrder($data){

		$msg = array();
		$arr = isset($_SESSION[USER_AGENT]) ? $_SESSION[USER_AGENT] : array();
		$address = $GLOBALS['User']->addAddr($data['addr'],false);


		$_SESSION[USER_AGENT]['message'] = $data['message'];

		if(!$GLOBALS['User']->checkAddr($address))
		{
			$msg[] = 'Shipping Address Incomplete!';
		}
		if(empty($arr['cart_goods']))
		{
			$msg[] ='There are no products in your shopping cart.';
		}
		if(empty($arr['grand']))
		{
			$msg[] =' Invalid order. ';
		}

		if(empty($arr['shipping']))
		{

			$_SESSION[USER_AGENT]['shipping'] = $this->getShipping();
		}
		if(empty($arr['payment']))
		{
			$_SESSION[USER_AGENT]['payment'] = $this->getPayment();
		}

		return $msg;
	}
	//取得订单号
	public function orderSn(){

		$order_sn = $GLOBALS['_CFG']['site_id'].'-'.date("Ymdhis",time());

		return $order_sn;
	}

	//取得未完成订单
	public function unOrder(){

		$cart  = $this->cartGoods();

		$sess_id = @$_COOKIE['ETH_SESS'];

		$sess_order = $this->counts("select count(*) from order_info where user_agent='".$sess_id."' and pay_status=0");

		if($sess_id && empty($cart['goods_list']) && $sess_order)
		{

			$addr = $GLOBALS['User']->getAddr();

			$order = $this->getCookieOrder($sess_id);

			$this->reOrder($order);
		}

	}
	//重新添加到购物车
	public function reOrder($order){

		$order_goods = $order['order_goods'];
		foreach($order_goods as $key=>$val)
		{
			$sp = preg_split("/,/",$val['goods_attr_id']);

			$this->addToCart($val['goods_id'],$val['goods_number'],$sp);
		}
	}
	//取得cookie订单
	public function getCookieOrder($sess_id){
		$sql = "select o.order_id,o.shipping_id,o.pay_id,o.goods_amount,o.shipping_fee,o.order_amount from order_info as o where o.user_agent='$sess_id' order by o.order_id desc";
		$data = $GLOBALS['db']->getRow($sql);
		if($data)
		{
			$data['order_goods'] = $this->orderGoods($data['order_id']);
		}
		return $data;
	}
	//取得订单信息
	public function orderList($start=0,$size=10,$where=' where 1'){
		$sql = "select * from
		order_info $where order by add_time desc limit $start,$size";

		$data = $GLOBALS['db']->getAll($sql);
		foreach($data as $key=>$val)
		{
			$val = $this->orderFormat($val);
			$val['order_goods'] = $this->orderGoods($val['order_id']);
			$r_id = $val['review_id'];
			$review = $GLOBALS['User']->reviewList(0,1," where type=3 and r_id=$r_id");

			$val['order_review'] = @$review[0];
			$data[$key] = $val;
		}
		//print_r($data);
		return $data;
	}
	//取得订单信息
	public function orderInfo($order_id){
		$sql = "select o.order_id,o.pay_status,o.order_sn,o.user_id,o.shipping_name,o.shipping_id,o.pay_id,o.goods_amount,o.discount,o.shipping_fee,o.order_amount,o.address,o.add_time
		from order_info as o where o.order_id='$order_id' order by o.order_id desc";
		$data = $GLOBALS['db']->getRow($sql);
		if(!$data)
		{
			return false;
		}
		$data = $this->orderFormat($data);

		return $data;
	}

	//格式化订单信息
	public function orderFormat($data){
		$address = @$this->json2Array(stripcslashes($data['address']));

		$data['goods_amountd'] = $this->priceFormat($data['goods_amount']);
		$data['discountd'] = $this->priceFormat($data['discount']);
		$data['shipping_feed'] = $this->priceFormat($data['shipping_fee']);
		$data['order_amountd'] = $this->priceFormat($data['order_amount']);
		$data['add_time'] = $this->dateFormat($data['add_time'],'Y-m-d H:i:s');
		$addre['addr_str'] = $GLOBALS['User']->addrStr($address);
		$addre['address'] = $address;
		$data['order_url'] = @$this->orderUrl($data['order_id'],$address['email']);
		$user = $GLOBALS['User']->userInfo(@$data['user_id']);
		$data['user'] = $user;
		$data['address'] = $addre;

		return $data;
	}
	//取得销售排行
	public function topOrder($start=0,$size=10){
		$sql = "select o.goods_id,g.goods_name,o.goods_sn,o.goods_number,o.market_price,o.goods_price as shop_price,o.goods_attr_id,o.goods_attr,g.original_img
		from order_goods as o inner join goods as g on o.goods_id=g.goods_id where 1 order by o.order_id desc limit $start,$size";
		//echo $sql;
		$data = $GLOBALS['db']->getAll($sql);
		foreach($data as $key=>$val)
		{
			$val = $GLOBALS['Goods']->goodsFormat($val);
			$data[$key] = $val;

		}

		return $data;

	}
	//取得order_goods
	public function orderGoods($order_id){
		$sql = "select o.goods_id,o.goods_name,o.goods_sn,o.goods_number,o.market_price,o.goods_price,o.goods_attr_id,o.goods_attr,g.original_img from order_goods as o inner join goods as g on o.goods_id=g.goods_id
		where o.order_id=$order_id";
		$data = $GLOBALS['db']->getAll($sql);
		foreach($data as $key=>$val)
		{
			$val['market_priced'] = $this->priceFormat($val['market_price']);
			$val['goods_priced'] = $this->priceFormat($val['goods_price']);
			$goods_thumb = $this->resizeImage(ROOT_PATH.$val['original_img'], array(250, 250));
			$val['url'] = $this->buildUri($val['goods_name'], $val['goods_id'], GOODS_NAME);
			$val['goods_thumb'] = preg_replace("#".preg_quote(ROOT_PATH)."#","",$goods_thumb);
			$data[$key] = $val;

		}

		return $data;

	}
	//增加到购物车 pack_goods_id ---套餐id
	public function addToCart($goods_id,$goods_number=1,$attr_ids=array(),$pack_goods_id=0){
		$goods = $GLOBALS['Goods']->goodsBasic($goods_id);
		$attrs = array();
		foreach($attr_ids as $key=>$val)
		{
			$attr = $GLOBALS['Goods']->attrOne($val);
			$attrs['values'][] = $attr['attr_name'].':'.$attr['attr_value'];
			$attrs['ids'][] = $val;
		}
		if($attr_ids)
		{
			$goods_attr = join($attrs['values'],"\n");
			$goods_attr_id = join($attrs['ids'],',');
		}
		else
		{
			$goods_attr = '';
			$goods_attr_id = '';
		}

		//如果该商品已经加入购物车（相同属性），那么只增加数量
		$rec_id = $this->sameCartGoods($goods_id,$goods_attr_id);
		if($rec_id)
		{
			$sql = "update cart set goods_number=".$goods_number."+goods_number where rec_id=$rec_id";
			mysql_query($sql);
			return true;
		}

		$sql = "insert into cart(`session_id`,`goods_id`,`goods_sn`,`goods_name`,`market_price`,`goods_price`,`goods_number`,`goods_attr`,`goods_attr_id`,`pack_goods_id`) values('".USER_AGENT."',
		'".$goods_id."','".$goods['goods_sn']."','".$this->escapeString($goods['goods_name'])."','".$goods['market_price']."','".$goods['shop_price']."','".$goods_number."',
		'".$this->escapeString($goods_attr)."','".$goods_attr_id."','".$pack_goods_id."')";

		mysql_query($sql);
		return true;
	}


	//判断加入购物车的是否是相同的商品
	private function sameCartGoods($goods_id,$goods_attr_id){
		$sql = "select rec_id from cart where goods_id=$goods_id and goods_attr_id='".$goods_attr_id."' and session_id='".USER_AGENT."'";
		return $GLOBALS['db']->getOne($sql);

	}
	//删除购物车
	public function dropCart($rec_id){
		$sql = "delete from cart where rec_id=$rec_id";
		$sql2 = "delete from order_goods whre rec_id=$rec_id";
		setCookie('ETH_SESS',"",time()-3600,'/ ');
		$res1 = mysql_query($sql);
		$res2 = mysql_query($sql2);
		return ($res1 && $res2);
	}
	//取得顶部购物车
	public function getTopCart(){
		$cart = $this->cartGoods();

		$goods_list['total']['subtotal'] = $cart['total']['goods_amountd'];

		$goods_list['total']['num']   = count($cart['goods_list']);
		$goods_list['list'] = $cart['goods_list'];

		return $goods_list;

	}
	//相同的订单 相同返回 true
	public function SameOrder(){
		$result = false;
		$order = @$_SESSION[USER_AGENT]['order'];
		$grand = @$_SESSION[USER_AGENT]['grand'];
		if(!empty($order))
		{
			$res = array();
			$orders = $this->getCookieOrder(USER_AGENT);
			if(intval($orders['shipping_fee'])==intval($grand['shipping_fee']))
			{
				$res[]=1;
			}
			if(intval($orders['goods_amount'])==intval($grand['subtotal']))
			{
				$res[]=1;
			}
			if(intval($orders['order_amount'])==intval($grand['grand']))
			{
				$res[]=1;
			}

			if(array_sum($res)==3)
			{
				$result =  true;
			}
			else
			{
				$result =  false;
			}


		}

		return $result;
	}

	//订单完成
	public function orderComplete($order_id){
		$sql = "update order_info set pay_status=2 where order_id=$order_id";
		$res = mysql_query($sql);
		return $res;
	}
	//取得订单
	public function getOrder(){
		$ua = $_SESSION[USER_AGENT];

		$addr = $this->json2Array($ua['address']);
		$address = $addr['address'];

		$shipping = $ua['shipping'];

		$payment = $ua['payment'];
		$grand = $ua['grand'];
		$cart_goods = $ua['cart_goods'];
		$message = $ua['message'];
		$order_sn = $this->orderSn();
		$order = array(
        'shipping_id' => $shipping['shipping_id'],
        'shipping_fee' => $grand['shipping_fee'],
        'shipping_name' => $shipping['name'],
        'goods_amount' => $grand['subtotal'],
        'order_amount' => $grand['grand'],
        'discount' => @$grand['discount'],
        'to_buyer' => $message,
        'pay_id' => $payment['pay_id'],
        'pay_name' => $payment['pay_name'],
        'pay_account' => $payment['account'],
        'address' => $this->escapeString(json_encode($address)) ,
        'user_agent' => USER_AGENT,
        'user_id' => $_SESSION['user_id'],
        'add_time' => time() ,
        'shipping_status' => 0,
        'pay_status' => 0,
		'order_sn'=>$order_sn,
		'ip'=>$_SERVER['REMOTE_ADDR'],
		'os'=>$this->getOs().'-'.$this->getBrowser()
		);
		if($order['goods_amount'] && $order['address'])
		{
			return $order;
		}
		else
		{
			return false;
		}


	}


	//插入订单和商品
	public function addOrder($order){
		$GLOBALS['db']->autoExecute('order_info', $order, 'INSERT');
		$order_id =  $GLOBALS['db']->insert_id();
		$sql = "INSERT INTO order_goods( order_id, goods_id, goods_name, goods_sn, goods_number, market_price, goods_price, goods_attr, goods_attr_id)
				SELECT '$order_id', goods_id, goods_name, goods_sn, goods_number, market_price,goods_price, goods_attr,goods_attr_id FROM cart WHERE session_id = '".USER_AGENT."'";

		mysql_query($sql);
		$res['order_id'] = $order_id;
		$res['order_sn'] = $order['order_sn'];
		setCookie('ETH_SESS',USER_AGENT,strtotime("+1 years"),'/ ');
		return $res;
	}
	//更新订单
	public function updateOrder($order,$order_id){
		 $sql = "update order_info set `discount` = '" . $order['discount'] . "',`to_buyer`='" . $order['to_buyer'] . "',
			 `pay_id`='" . $order['pay_id'] . "',`address`='" . $order['address'] . "',`user_id`='" . $order['user_id'] . "' where order_id=$order_id";
        return mysql_query($sql);
	}
	//删除购物车
	public function clearCart(){
		$sql = "delete from cart where session_id='".USER_AGENT."';";
		mysql_query($sql);
	}
	//取得支付代码
	public function payCode($order,$code='paypal'){
		include_once (INC_PATH.'/class/payment/'.$code.'.php');
		$obj = new $code;
        $pay = $obj->get_code($order);
		return $pay;
	}
	//支付验证
	public function payCheck($code='paypal'){
		 $plugin_file = INC_PATH.'/class/payment/' . $code . '.php';
		 include_once($plugin_file);
		 $payment = new $code;
		 return $payment->respond();
	}
	//允许查看订单信息
	public function canBePayres($order_info){
		if(!$order_info)
		{
			die();
		}

		if(empty($_GET['amt']) && empty($_GET['st']) && empty($_GET['cc']) && empty($_GET['tx']))
		{
			$res[]= 0;
		}
		else
		{
			$res[] = 1;
		}

		if(@$_GET['email'] != @$order_info['address']['address']['email'])
		{
			$res[]= 0;
		}
		else
		{
			$res[] =1;
		}
		if(array_sum($res)==0)
		{
			die();
		}
	}
	//取得再次支付的url
	public function orderUrl($order_id,$email){
		$url = $GLOBALS['host'].'/checkouts.php?act=payres&cd=paypal&o_id='.$order_id.'&email='.$email;
		return $url;
	}
	//取得时间段内的订单
	public function durOrder($days){

		if(!$days) $days = $GLOBALS['db']->getRow("select max(add_time) as end,min(add_time) as start from order_info");
		$dur = $this->during($days);
		$chart = array();
		foreach($dur as $key=>$val)
		{

			$payed = 0;
			$start = $val['start'];
			$end = $val['end'];

			$order = $GLOBALS['db']->getAll("select pay_status from order_info where add_time>='$start' and add_time<='$end'");

			foreach($order as $o_k=>$o_v)
			{
				if($o_v['pay_status']==2)
				{
					$payed+=1;
				}
			}
			$cats[] =  sprintf('%s',$this->dateFormat($val['start'],'m d'));
			$order_num[] =  count($order);
			$order_payed[] =  $payed;
		}

		$names = array('总订单','已付款');
		$datas = array($order_num,$order_payed);
		$chart = $this->chartData($cats,$names,$datas);




		return $chart;

	}




}

?>